<?php 	
/**
 * 大富翁
 */  
class allChips {
    //往期揭晓
    public static function getWinList($pid){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $periodModule = M("module_mill_period");
        Session::switchCustomer($customerId);
        $result = $periodModule->alias("a")
            ->join("left join wx_module_mill_number b on a.wNumber=b.number and b.perId=a.id")
            ->join("left join wx_".$customerId."_user_weixin_info c on b.openId = c.openid")
            ->join("left join wx_module_mill_par d on b.openId=d.openId and d.perId = a.id")
            ->field("a.id,a.perNumber,a.updataTime,a.periodState,b.number,d.count,d.ip,d.city,c.nickname,c.headimgurl")
            ->where("a.pid = $pid and (a.periodState = '2' or a.periodState = '3')")
            ->group("a.id")
            ->order("a.id desc")
            ->select();
        $arr['list'] = $result;
        Output::instance()->module("allChips","index")->object($arr);
    }
    public static function buyHistoryList($periodId,$start=0,$limit=20){
        $customerId = Session::$user['customerId'];
        $userName = Session::$user['userName'];
        Session::switchCustomer(0);
        $parModel = M("module_mill_par");
        Session::switchCustomer($customerId);
        $arr=$parModel->alias("par")
            ->join("inner join wx_module_product_order b on par.oid=b.id")
            ->join("left join wx_".$customerId."_user_weixin_info u on par.openId=u.openid")
            ->where("par.perId=$periodId and (b.status = 'partake' or b.status = '".order_status_ok."' or b.status = '".order_status_delivered."' or b.status = '".order_status_refund."' or b.status = '".ORDER_STATUS_REFUNDEDPART."')")
            ->field("par.perId,par.count,par.ip,par.city,u.nickname,u.headimgurl,par.createTime as updateTime")
            ->group("par.id")
            ->order("par.updateTime desc")
            ->limit($start,$limit)->select();
        Output::instance()->object($arr);
    }
    //创建参与记录
    public static function createParRecord($periodId,$oid,$pid,$count,$periodCount,$openId){
        $customerId = Session::$user['customerId'];
        $userName = Session::$user['userName'];
        Session::switchCustomer(0);
        $parModule = M("module_mill_par");
        $numberModule = M("module_mill_number");
        $orderModule = M("module_product_order");
        Session::switchCustomer($customerId);
        $newParId=null;
        for($key=0;$key<$periodCount;$key++){
            $data["openId"] = $userName;
            $data["count"] = $count/$periodCount;
            $data["pid"] = $pid;
            if($key==0){
                $data["parState"] = "1";
                $data["perId"] = $periodId;
            }else{
                $data["perId"] = NULL;
                $data["parState"] = "0";
            }
            $data["oid"] = $oid;
           if($openId&&$openId!=$userName){
               $data["fromOpenId"] = $openId;
           }
            $data["ip"] = self::getIp();
            $data["city"] = self::getCityByIp($data["ip"]);
            $data["fromCustomerId"] = $customerId;
            $data["createTime"] = date('Y-m-d H:i:s',time());
            $data["updateTime"] = date("Y-m-d H:i:s",time());
            $parModule->startTrans();
            $parId = $parModule->add($data);
            Log::write("写入参与表".$parModule->getLastSql());
            if($parId==false){
                $parModule->rollback();
                Output::instance()->resultCode(code_sql_error);
                return;
            }
            $parModule->commit();
            if($key==0){
                $newParId = $parId;
                $orderModule->where("id=".$oid)->setField("playOrderId",$parId);
            }
        }
        $out=new stdClass();
        if($newParId){
            $out->code=0;
            $out->parId=$newParId;
        }else{
            $out->code=1;
        }
        Output::instance()->object($out);
    }
    //支付成功跳转
    public static function indianaSuccess($parId){
        $customerId = Session::$user['customerId'];
        $userName = Session::$user['userName'];
        $mallModel=M("module_mall_store");
        Session::switchCustomer(0);
        $parModule = M("module_mill_par");
        Session::switchCustomer($customerId);
        $userModel = M("user");
        $arr= $parModule->alias("a")
            ->join("inner join wx_module_mill_number b on a.id=b.parId")
            ->join("inner join wx_module_product c on a.pid = c.id")
			->join("inner join wx_module_mill_period d on a.perId = d.id")
            ->where("a.id=".$parId)
            ->field("c.id,c.name,GROUP_CONCAT(b.number) as number,a.count,a.perId,d.perNumber")
            ->group("a.id")
            ->find();
        $userInfo = $userModel->where("userName='".$userName."'")->find();
        if($userInfo["status"]=='unsubscribe'){
            $arr["subscribe"] = 0;
        }else{
            $arr["subscribe"] = 1;
        }
        $arr["number"] = explode(",",$arr["number"]);
        $mallResult=$mallModel->find();
        $arr["mall"]=$mallResult;
        Output::instance()->module("allChips","indianaSuccess")->object($arr);
    }
    //获取图文详情
    public function graphicDetail($pid){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $productModule = M("module_product");
        Session::switchCustomer($customerId);
        $out = $productModule->where("id=".$pid)->field("webPageContent")->find();
//        $out["webPageContent"] =  html_entity_decode(htmlentities($out["webPageContent"]));
        Output::instance()->module("allChips","graphicDetail")->object($out);
    }
    //计算详情
    public function calculation($perId){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $periodModule = M("module_mill_period");
        $parModule = M("module_mill_par");
        $lotteryModule = M("module_mill_lottery");
        Session::switchCustomer($customerId);
        $result =$periodModule->alias("a")
            ->join("inner join wx_module_product b on a.pid=b.id")
            ->where("a.id=".$perId)->field("a.timeTogether,b.name")->find();
        $timeList = $parModule->alias("a")
            ->join("wx_module_product_order b on a.oid=b.id")
            ->join("wx_".$customerId."_user_weixin_info c on a.openId=c.openid")
            ->where("a.perId=".$perId." and (b.status = 'partake' or b.status = '".order_status_ok."' or b.status = '".order_status_delivered."' or b.status = '".order_status_refund."' or b.status = '".ORDER_STATUS_REFUNDEDPART."')")
            ->field("a.updateTime,c.nickname")->order("a.id desc")->limit(0,50)->select();
        foreach($timeList as $key=>$value){
            $h = date("H",strtotime($value["updateTime"]));
            $m = date("i",strtotime($value["updateTime"]));
            $s = date("s",strtotime($value["updateTime"]));
            $timeList[$key]["number"] = $h.$m.$s;
        }
        $result["timeList"] = $timeList;
        $result["lottery"] = $periodModule->alias("a")
                        ->join("inner join wx_module_mill_lottery b on a.lotteryId = b.id")
                        ->field("a.periodState,a.wNumber,b.lotteryPerId,b.lotteryNumber")
                        ->where("a.id=".$perId)
                        ->find();
        $result["lottery"]["lotteryNumber"] = implode("",explode(",",$result["lottery"]["lotteryNumber"]));
        Output::instance()->module("allChips","calculation")->object($result);

    }
    //夺宝详情
    public function indianaDetail($oid){
        $customerId = Session::$user['customerId'];
        $userName = Session::$user['userName'];
        Session::switchCustomer(0);
        $periodModule = M("module_mill_period");
        $orderModule = M("module_product_order_detail");
        Session::switchCustomer($customerId);
        $where["b.oid"]=array("eq",$oid);
        $arr["list"] = $periodModule->alias("a")
            ->join("inner join wx_module_mill_par b on b.perId = a.id")
            ->join("inner join wx_module_mill_number c on c.parId = b.id")
            ->join("left join wx_module_mill_number e on (a.wNumber = e.number and e.perId = a.id)")
            ->join("left join wx_".$customerId."_user_weixin_info d on e.openId = d.openid")
            ->join("left join wx_module_mill_par f on e.parId = f.id")
            ->field("a.id,a.pid,a.perNumber,a.periodState,a.updataTime,a.wNumber,group_concat(distinct(c.number)) as number,f.ip,f.city,d.nickname")
            ->where($where)
            ->group("a.id")
            ->select();
        foreach($arr["list"] as $key=>$value){
            $arr["list"][$key]["number"] = explode(",",$value["number"]);
            $arr["list"][$key]["count"] = count($arr["list"][$key]["number"]);
        }
        Output::instance()->module("allChips","indianaDetail")->object($arr);
    }
    //最新揭晓
    public function newAnnounced($start=0,$limit=10){
        $customerId = Session::$user['customerId'];
        $userName = Session::$user['userName'];
        Session::switchCustomer(0);
        $periodModule = M("module_mill_period");
        $numberModule = M("module_mill_number");
        $parModule = M("module_mill_par");
        Session::switchCustomer($customerId);
        $list = $periodModule->alias("a")
            ->join("inner join wx_module_product b on a.pid = b.id")
            ->field("a.id,a.perNumber,a.wNumber,a.periodState,a.updataTime,b.id as pid,b.name,b.picUrl")
            ->limit($start,$limit)
            ->select();
        foreach($list as $key => $value){
            $winnerInfo = $numberModule->alias("a")
                ->join("inner join wx_module_mill_par b on a.parId=b.id")
                ->join("left join wx_".$customerId."_user_weixin_info c on b.openId = c.openid")
                ->join("left join wx_".$customerId."_user_weixin_info d on b.fromOpenId = d.openid")
                ->join("left join wx_module_mill_number e on (a.perId = e.perId and b.openId = e.openId)")
                ->join("left join wx_module_mill_number f on (a.perId = f.perId and b.fromOpenId = f.openId)")
                ->field("b.openId,b.fromOpenId,c.nickname as winnerName,d.nickname as recName,group_concat(e.number) as winnerNumber,group_concat(f.number) as recNumber")
                ->where("a.perId=".$value["id"])
                ->find();
            $list[$key]["winnerName"] = $winnerInfo["winnerName"];
            $list[$key]["recName"] = $winnerInfo["recName"];
            $list[$key]["winnerCount"] = count(explode(",",$winnerInfo["winnerNumber"]));
            $list[$key]["recCount"] = count(explode(",",$winnerInfo["recNumber"]));
        }
        $result["list"] = $list;
        Output::instance()->module("allChips","newAnnounced")->object($result);
    }
    //获得IP
    public function getIp() {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) $ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) $ip = $_SERVER['REMOTE_ADDR'];
        else $ip = "unknown";
        return ($ip);
    }
    //通过ip获得城市
    public static function getCityByIp($ip){
        $ch = curl_init();
        $url = "http://apis.baidu.com/apistore/iplookupservice/iplookup?ip=".$ip;
        $header = array(
            'apikey: 1de79f0ef2b3aa846bd81dd322d48c6a'
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 执行HTTP请求
        curl_setopt($ch , CURLOPT_URL , $url);
        $res = curl_exec($ch);
        $result = json_decode($res, true);
        if(!$result['retData']['city']||$result['retData']['city']=="None"){
            $result['retData']['city']="未知地区";
        }
        return $result['retData']['city'];
    }
}